package com.scommunity.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.pagehelper.PageInfo;
import com.scommunity.common.ResponseResult;
import com.scommunity.domain.Owner;
import com.scommunity.domain.Pay;
import com.scommunity.domain.User;
import com.scommunity.service.IOwnerService;
import com.scommunity.service.IPayService;
import com.scommunity.utils.Alipay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.*;

@RestController
@RequestMapping("/admin/pay")
public class PayController {
    /*@Autowired
    Alipay alipay;*/
    /*@Autowired
    SnowflakeIdWorker snowflake;*/
    @Autowired
    Alipay alipay;
    @Autowired
    IOwnerService ownerService;

    @Autowired
    private IPayService payService;
    @RequestMapping("/delete")
    public ResponseResult delete(@RequestParam Long payId){
        boolean b = payService.removeById(payId);
        if (b){
            return ResponseResult.success();
        }
        return ResponseResult.error(400,"删除失败");
    }
    @RequestMapping("/getAllpay")
    public ResponseResult getAllPay() {
        List<Pay> list = payService.list();
        return ResponseResult.success(list);
    }
    //pay还是需要分页
    @RequestMapping("/getAll")
    public ResponseResult getPageAllPay(@RequestParam Integer pageNum,@RequestParam Integer pageSize) {
        //System.out.println(pageNum+".."+pageSize);
        IPage<Pay> payList = payService.findPage(pageNum,pageSize);

        return ResponseResult.success(payList);
    }
    @RequestMapping("/getPageByCondition")
    public ResponseResult getPageByCondition(@RequestBody Pay pay,@RequestParam Integer pageNum,@RequestParam Integer pageSize) {
       // System.out.println(pay);
        PageInfo<Pay> page = payService.findPageByCondition(pageNum, pageSize, pay);
        return ResponseResult.success(page);
    }
    @RequestMapping("/add")
    public ResponseResult createPay(@RequestBody Pay pay){
        String payNum = String.valueOf(System.currentTimeMillis());
        pay.setPayNum(payNum);
        //补全pay数据
        payService.save(pay);
        return ResponseResult.success();
    }
    @RequestMapping("/updatePay")
    public ResponseResult updatePayUpdate(@RequestBody Pay pay){
        //这个可以用mq去实现延时消费
        boolean b = payService.updateById(pay);
            if (b){
                return ResponseResult.success();
            }
        return ResponseResult.error(400,"修改失败");
    }
    //测试
   /* @SneakyThrows
    @RequestMapping("/toopay")
    public String pay(){
        AliPayBean aliPayBean = new AliPayBean();
        aliPayBean.setOut_trade_no("1113334424333");
        aliPayBean.setSubject("平板");
        aliPayBean.setTotal_amount("222.8");
        aliPayBean.setBody("支付测试");
        String result = alipay.pay(aliPayBean);
        return result;
    }*/
    @RequestMapping("/topay")
    public ResponseResult getTopay(@RequestBody Pay pay){
        System.out.println(pay);
        //支付订单
        String result = payService.toPay(pay);
        return ResponseResult.success(result);
    }
        //支付宝回调通知
    @RequestMapping("/success")
    @ResponseBody
    public void success(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
      // Map<String,String> params =convertRequestParamsToMap(request);
        Map<String, String[]> aliParams = request.getParameterMap();

       /* System.out.println(aliParams.toString());*/
      /* String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "utf-8");
        System.out.println(trade_status);*/
        // 用以存放转化后的参数集合
        Map<String, String> conversionParams = new HashMap<String, String>();
        for (Iterator<String> iter = aliParams.keySet().iterator(); iter.hasNext();) {
            String key = iter.next();
            String[] values = aliParams.get(key);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            conversionParams.put(key, valueStr);
        }
//		logger.info("==================返回参数集合：" + conversionParams);
        System.out.println(conversionParams);
        String status = alipay.notify(conversionParams);
        System.out.println(status);

    }
    // 将request中的参数转换成Map
    private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }
    @RequestMapping("/myPays")
    public ResponseResult getMyPays(@SessionAttribute User user, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
       //
       Long userId = user.getUserId();
        Owner owner = ownerService.getOne(new QueryWrapper<Owner>().eq("user_id", userId));
        Long ownerId = owner.getOwnerId();
        Pay pay = new Pay();
        pay.setOwnerId(ownerId);
        PageInfo<Pay> page = payService.findPageByCondition(pageNum, pageSize, pay);

        return ResponseResult.success(page);
    }



}
